<template>
  <div class="patientCard-container">
    <div class="nav-btn">
      <el-dropdown v-if="!risk">
        <el-button type="text">
          更多菜单
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="tools('转诊')">转诊</el-dropdown-item>
            <el-dropdown-item v-if="isShowCloas" @click="closeVisit()">
              结束就诊
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- <el-button class="nav-btn" type="text">转诊</el-button> -->
    <div class="header-container">
      <avatar
        style="position: absolute"
        :src="patientInfo.headPortrait"
        :userId="id"
      ></avatar>
    </div>
    <h3 style="text-align: center; margin: 14px auto" @click="showQrCode">
      {{ patientInfo && patientInfo.name }}
      <svg-icon icon-class="qrcode"></svg-icon>
    </h3>
    <span style="display: block; text-align: center">
      ID:{{ patientInfo && patientInfo.id }}
    </span>
    <span style="display: block; text-align: center">
      {{ patientInfo && (patientInfo.sex ? '男' : '女') }}
      {{ patientInfo && patientInfo.ageName }}
    </span>
    <h4>
      <svg-icon
        class-name="stethophone-icon"
        icon-class="stethophone"
      ></svg-icon>
      体征数据
    </h4>
    <span class="signs-title">{{ patientInfo.signs }}</span>

    <div class="steps-container" v-if="!(risk || isPatientInfo)">
      <el-steps :active="100" align-center>
        <el-step
          v-for="(item, index) in beforeEmrStatus"
          :key="index"
          :title="item.title"
          :description="item.statusTitle"
          :status="item.status"
        >
          <!-- <slot name="icon"><span>1212</span></slot> -->
          <template v-slot:icon>{{ index + 1 }}</template>
        </el-step>
      </el-steps>
      <el-steps :active="100" align-center style="margin-top: 20px">
        <el-step
          v-for="(item, index) in afterEmrStatus"
          :key="index"
          :title="item.title"
          :description="item.statusTitle"
          :status="item.status"
        >
          <!-- <slot name="icon"><span>1212</span></slot> -->
          <template v-slot:icon>{{ index + 4 }}</template>
        </el-step>
      </el-steps>
    </div>
    <template v-if="!risk">
      <el-divider style="margin: 36px auto 12px" content-position="center">
        历史病历
      </el-divider>
      <el-menu
        :default-active="pageData.activeIndex"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
      >
        <!-- <el-menu-item index="3" disabled>Info</el-menu-item>
      <el-menu-item index="4">Orders</el-menu-item> -->
        <el-menu-item index="0">门诊</el-menu-item>
        <el-menu-item index="1">住院</el-menu-item>
      </el-menu>
      <el-collapse v-if="activities.length > 0" v-model="defaultexpandedkeys">
        <el-collapse-item
          v-for="(activity, index) in activities"
          :key="index"
          :name="activity.id"
        >
          <template #title>
            <div class="doctor-cell">
              <span>{{ activity.label }}</span>
              <span>{{ renderDay(activity.time) }}</span>
            </div>
          </template>
          <el-timeline v-if="activity.children.length > 0" class="timeline">
            <el-timeline-item
              v-for="(item, index) in activity.children"
              :key="index"
              placement="top"
              :timestamp="renderTime(item.recordDate)"
              color="#0bbd87"
            >
              <div class="doctor-cell">
                <span class="doctor-title">
                  <div class="doctor-content">
                    <span>病历ID:</span>
                    <el-button
                      type="text"
                      style="height: 25px; padding: 2px"
                      @click="updateRouter(item)"
                    >
                      {{ item.id }}
                    </el-button>
                  </div>

                  <div>接诊医生: {{ item.doctorName }}</div>
                  <div>
                    病历属性: {{ item.treatmentType === 1 ? '首诊' : '复诊' }}
                  </div>
                  <div>
                    诊断: {{ item.diagnosis ? item.diagnosis : '暂无数据' }}
                  </div>
                  <div>
                    评估: {{ item.evaluate ? item.evaluate : '暂无数据' }}
                  </div>
                </span>
              </div>
            </el-timeline-item>
          </el-timeline>
          <el-button
            v-else
            type="text"
            class="more-btn"
            :class="{ 'all-data': pageData.isAll }"
          >
            {{ '暂无更多数据' }}
          </el-button>
        </el-collapse-item>
      </el-collapse>
      <el-button
        v-else
        type="text"
        class="more-btn"
        :class="{ 'all-data': pageData.isAll }"
      >
        {{ '暂无更多数据' }}
      </el-button>
    </template>
  </div>
</template>
<script>
  import { computed, onBeforeMount, reactive, ref } from '@vue/runtime-core'
  import { useStore, mapGetters } from 'vuex'
  import { useRoute, useRouter } from 'vue-router'
  import filter from '@/hooks/filter.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    modifyVisit,
    loadHistoricalVisitTree,
    getEmrStatus,
  } from '@/api/modules/patient'
  import SvgIcon from '../SvgIcon/index.vue'
  import { useRouteAndRouter } from '@/hooks/core/useRouteAndRouter.js'
  import common from '../../utils/common'
  import { useRouters } from '@/hooks/core/useRouters'
  export default {
    name: 'PatientCard',
    props: { id: Number, userInfo: Object },
    computed: {
      ...mapGetters(['patientInfo', 'beforeEmrStatus', 'afterEmrStatus']),
    },
    setup(props) {
      const store = useStore()
      const route = useRoute()
      const router = useRouter()

      const { openNewWindow } = useRouters()
      const pageData = reactive({
        userInfo: [],
        activeIndex: route.query.vtype === '1' ? '1' : '0',
        isAll: false,
      })
      const loadPatientInfo = async function (id) {
        await store.dispatch('patient/loadPatientInfo', id)
      }
      const loadEmr = async function (pid, type) {
        let res = null
        if (pid && type) {
          res = await store.dispatch('patient/getEmrHistory', {
            pid: pid,
            search: { pageIndex: 1, pageSize: 3, type: type },
          }) // type 0 门诊, 1 住院
        } else {
          res = await store.dispatch('patient/getEmrHistory', { pid: pid })
        }
        pageData.isAll = false
        if (res && res.data.length < res.search.pageSize) {
          pageData.isAll = true
        }
      }
      const showQrCode = async function () {
        const qrObject = {
          config: { showTextbar: false },
          data: [
            {
              name: '用户信息',
              text: [
                // eslint-disable-next-line max-len
                `https://devtest.c-sams.com/qrcode?pid=${props.id}&orgId=${store.getters.userInfo.orgId}&userId=${store.getters.userInfo.userId}&scanType=1`,
              ],
            },
          ],
        }
        // 主节点url+患者id ""
        store.dispatch('qrcode/setQRCodeShowData', qrObject)
      }

      const activities = computed(() => {
        return store.getters.visitHistoricals
      })
      const defaultexpandedkeys = ref([])

      const { isRiskRx, isPatientInfoRx } = useRouteAndRouter()
      const risk = isRiskRx
      const isPatientInfo = isPatientInfoRx()
      const loadData = async function (pid, type) {
        // TODO TODO 开发注入那一套 全局坚挺
        store.dispatch('patient/loadHistoricalVisitInfo', {
          patientId: pid,
          type,
          pageIndex: 1,
          pageSize: 1000,
          riskScreeningType: 0,
        })
        defaultexpandedkeys.value = [parseInt(route.query.vid)]
      }

      const pid = ref(null)
      onBeforeMount(() => {
        pid.value = props.id
        loadPatientInfo(props.id)
        loadData(props.id, pageData.activeIndex)
        store.dispatch('patient/loadEmrStatus', {
          medicalRecordId: route.query.emrId,
          patientId: route.query.id,
        })
      })

      const updateRouter = function (activity) {
        const getQuery = function () {
          let query = {}
          if (route.query.id) query['id'] = route.query.id
          query['vid'] = activity.historicalVisitId
          query['vtype'] = pageData.activeIndex
          query['emrId'] = activity.id
          query['timer'] = Date.parse(new Date())
          return query
        }
        if (
          activity.id + '' === route.query.emrId &&
          route.query.emrId !== undefined
        ) {
          common.XmAlert(
            '已在当前病历下，是否继续刷新页面（需要保存未完成的工作哦）',
            () => {
              router.push({ name: 'medicalRecord', query: getQuery() })
              // openNewWindow('medicalRecord', getQuery())
              // location.reload()
            }
          )
          return
        }

        router.push({ name: 'medicalRecord', query: getQuery() })
        // openNewWindow('medicalRecord', getQuery())
        // location.reload()
      }
      const handleSelect = function (type) {
        pageData.activeIndex = type
        loadData(props.id, type)
      }
      const { renderTime, renderHour, renderDay } = filter() //, routerFilter
      const closeVisit = function () {
        const historicalVisitId = route.query.vid
        if (!historicalVisitId) return
        ElMessageBox.confirm(
          '是否结束当前就诊，注意：不会主动改变病历状态',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(async () => {
          const params = { historicalVisitId, status: 3 }
          const res = await modifyVisit(params)
          if (!res || res.code !== '0000') return
          ElMessage({
            type: 'success',
            message: '结束就诊成功',
          })
          router.go(-1)
        })
      }

      const isShowCloas = computed(() => {
        return route.query.vid ? true : false
      })
      return {
        activities,
        // signTitle,
        pageData,
        handleSelect,
        loadEmr,
        renderTime,
        renderHour,
        renderDay,
        updateRouter,
        closeVisit,
        isShowCloas,
        showQrCode,
        defaultexpandedkeys,
        risk,
        isPatientInfo,
        pid,
      }
    },
    components: { SvgIcon },
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/mixin.scss';
  $pwidth: 275px;
  .patientCard-container {
    background-color: white;
    overflow: hidden;
    position: relative;
    border-radius: 5px;
    padding: 11px;
    @include card-shadow;

    width: $pwidth;

    h4 {
      font-size: 16px;
      font-weight: 500;
    }
    .signs-title {
      font-size: 16px;
      padding: 4px 12px;
    }
    .stethophone-icon,
    branch-icon {
      fill: 000000;
    }
    .nav-btn {
      position: absolute;
      right: 11px;
      overflow: hidden;
      color: red;
    }
    .more-btn {
      margin: 0 auto;
      display: block;
    }
    .all-data {
      color: var(--el-text-color-secondary);
    }
    .header-container {
      margin: 50px auto 11px;
      width: 50%;
      height: 0;
      position: relative;
      padding-bottom: 50%;
      border-radius: 100%;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
        position: absolute;
      }
    }
    .steps-container {
      margin: 25px 0px;
      :deep(.el-step__title) {
        font-size: 12px;
        line-height: 18px;
      }
      // .el-step__description.is-finish {
      //   color: var(--el-color-primary);
      // }
    }
    .el-menu-item {
      width: 130px;
      text-align: center;
      height: 40px;
      line-height: 40px;
    }
    span {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }
    p {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }
    .doctor-cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding-right: 20px;
      .doctor-title {
        font-size: 12px;
        color: #606266;
        .doctor-content {
          display: flex;
          align-items: center;
        }
      }
      :deep(.el-tree-node__expand-icon) {
        padding: 0px !important;
      }
    }
  }
</style>
